<template>
  <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" append-to-body title="试题列表" width="800px"
             :visible.sync="show" @closed="resetDialogMain">
    <div class="wrapper">
      <div>
        <el-button @click="showAdd=true" size="small">添加题目</el-button>
        <el-button @click="showAdds=true" type="primary" size="small">批量添加题目</el-button>
        <el-button @click="onSave" type="success" size="small">保存</el-button>
        <span class="annotation">（每次操作需要手动点击保存按钮,以免造成数据丢失）</span>
      </div>
      <!-- 表格数据 -->
      <el-table style="margin-top: 15px" :data="tableData" border>
        <el-table-column prop="id" label="ID" width="50" align="center"/>
        <el-table-column prop="title" show-overflow-tooltip label="题目" align="center"/>
        <el-table-column prop="type" width="100" label="类别" align="center">
          <template v-slot="{ row }">
            {{ row.type === "radio" || row.type == "redio" ? "单选" : "判断" }}
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案" width="100" align="center"/>
        <el-table-column label="操作" width="130" align="center" fixed="right">
          <template v-slot="{ row,$index }">
            <el-button type="text" title="编辑" @click="handle(row)">编辑</el-button>
            <el-button type="text" title="删除" @click="deleteRow($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" append-to-body :title="(findData.edit ? '编辑' : '添加') +'试题'" width="600px" :visible.sync="showAdd"
               @closed="resetDialog">
      <el-form size="small" class="formRow" label-position="top">
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="题目" prop="title">
              <el-input size="small" v-model="findData.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="type">
              <el-radio-group size="small" v-model="findData.type" @change="typeChange">
                <el-radio label="radio">单选</el-radio>
                <el-radio label="judge">判断</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="答案" prop="answer">
              <el-select class="w100" size="small" v-model="findData.answer" placeholder="请选择答案">
                <el-option
                    v-for="li in findData.options"
                    :key="li.value"
                    :label="li.value"
                    :value="li.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">

          <el-col :span="24">
            <el-form-item label="解析" prop="analysis">
              <el-input size="small" type="textarea" :autosize="{minRows: 2, maxRows: 4}"
                        v-model="findData.analysis"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="选项" prop="options">
          <el-button @click="addQuestions" v-if="findData.type == 'radio'">添加选项</el-button>
          <div v-if="findData.type == 'radio'" class="flex" style="width: 100%;margin-top: 10px"
               v-for="(li,i) in findData.options" :key="i">
            <el-input class="icenter" readonly size="small"
                      :value="getLetterFromNumber(i)"></el-input>
            <el-input class="flex1" placeholder="选项说明" style="margin-left: 10px" size="small"
                      v-model="li.title"></el-input>
            <el-button style="margin-left: 10px" type="text" @click="deleteQuestions(i)">删除</el-button>
          </div>
          <div v-if="findData.type == 'judge'" class="flex" style="width: 100%;margin-top: 10px"
               v-for="(li,i) in findData.options" :key="i">
            <el-input  class="icenter" readonly size="small"
                      :value="li.value"></el-input>
            <el-input class="flex1" placeholder="选项说明" style="margin-left: 10px" size="small"
                      v-model="li.title"></el-input>
          </div>
        </el-form-item>
        <el-button class="w100" type="primary" size="small" @click="onSubmit">提交</el-button>
      </el-form>
    </el-dialog>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" append-to-body title="批量添加试题" width="600px" :visible.sync="showAdds"
               @closed="resetDialog">
      <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 12}" class="w100" v-model="text"></el-input>
      <el-button slot="footer" @click="onJiexi" type="primary" size="small">提交</el-button>

    </el-dialog>

  </el-dialog>

</template>

<script>
import {
  Add_question_information,
  Delete_question_information,
  Querying_question_Information,
  updatequestion_Information,
  jiexiquestion
} from "@/api"

const defaultValue = {
  title: "",
  // 类别 radio 单选 judge 判断
  type: "radio",
  // 答案
  answer: "",
  // 解析
  analysis: "",
  options: []
}
export default {
  name: "questions_list",
  props: {},
  data() {
    return {
      show: false,
      showAdd: false,
      showAdds: false,
      text:"",
      id: "",
      tableData: [],
      // 操作的数据信息
      findData: {
        title: "",
        // 类别 radio 单选 judge 判断
        type: "radio",
        // 答案
        answer: "",
        // 解析
        analysis: "",
        options: []
      },
    }
  },
  methods: {
    // 解析批量提交题目
    onJiexi(){
      jiexiquestion({
        Text: encodeURIComponent(this.text)
      }).then(data => {
        console.log(data);
        this.text = '';
        this.showAdds = false;
        if(data.length > 0){
          data.forEach(item => {
            this.tableData.unshift(item);
          })
        }
      })
    },
    typeChange(e) {
      console.log(e)
      if (e === "radio") {
        this.findData.options = [];
      } else if (e === "judge") {
        this.findData.options = [
          {
            title: "正确",
            value: "正确"
          },
          {
            title: "错误",
            value: "错误"
          }
        ]
      }
    },
    // 编辑试题
    handle(row) {
      console.log(row)
      this.findData = {
        ...row,
        edit: true
      }
      this.showAdd = true;
    },
    // 表格删除一行数据
    deleteRow(index) {
      this.tableData.splice(index, 1);
    },
    // 试题删除一条数据
    deleteQuestions(index) {
      this.findData.options.splice(index, 1);
      this.findData.options.forEach((item, index) => {
        item.value = this.getLetterFromNumber(index)
      })
    },
    // 添加一条试题
    addQuestions() {
      this.findData.options.push({
        title: "",
        value: ""
      })
      this.findData.options.forEach((item, index) => {
        item.value = this.getLetterFromNumber(index)
      })
    },
    // 将数字映射到字母
    getLetterFromNumber(num = 0) {
      return String.fromCharCode(65 + num);
    },
    open(id) {
      console.log(id)
      this.id = id;
      if (id) {
        Querying_question_Information({id}).then(res => {
          console.log(res)
          this.tableData = JSON.parse(res[0].content)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    resetDialogMain() {
      this.tableData = [];
      this.resetDialog();
    },
    resetDialog() {
      this.findData = JSON.parse(JSON.stringify(defaultValue));
    },
    // 新增 修改
    onSubmit() {
      let params = {
        ...this.findData
      }
      if (!params.id) {
        params.id = this.tableData.length + 1;
      }
      this.tableData.unshift(params);
      this.showAdd = false;
    },
    // 保存
    onSave() {
      let content = JSON.stringify(this.tableData);
      console.log(content)
      if (this.id) {
        // 修改
        updatequestion_Information({
          id: this.id,
          content
        }).then(res => {
          console.log(res)
          this.$message.success("保存成功");
        })
      } else {
        // 新增
        Add_question_information({
          content
        }).then(res => {
          let id = res.data[0].id;
          console.log(id)
          this.$message.success("保存成功");
          this.$emit("change", id)
        })
      }

    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  .list {
    .item {
      .label_for {
        margin-bottom: 15px;

        .label {
          padding: 10px 0;
        }
      }
    }
  }
}

.icenter{
  width: 80px;
  ::v-deep.el-input__inner{
    text-align: center;
  }
}
</style>
